package com.nuoniu.sibanyun.interceptor.handler;

import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.config.JwtUtils;
import com.nuoniu.sibanyun.service.impl.SysLogServiceImpl;
import com.nuoniu.sibanyun.service.redis.RedisService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName MyLogoutHandler
 * @Description 用户注销逻辑处理
 * @Authpr baiqiang
 * @Date 2020/8/1 16:34
 **/
@Component
public class MyLogoutHandler implements LogoutHandler {

    @Autowired
    private RedisService redisService;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private SysLogServiceImpl logService;
    @Override
    public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
        String tokenHeader = httpServletRequest.getHeader(JwtUtils.TOKEN_HEADER);
        // 如果请求头中没有Authorization信息则直接放行了
        if (tokenHeader != null && tokenHeader.startsWith(JwtUtils.TOKEN_PREFIX)) {
            String token = tokenHeader.replace(JwtUtils.TOKEN_PREFIX, "");
            Claims body = jwtUtils.checkToken(token);
            String userName = body.getSubject();
            //保存登录日志
            if(StringUtils.isNotBlank(userName)){
                long time = System.currentTimeMillis();
                logService.saveLog(userName, time, "用户注销登录", httpServletRequest);
                jwtUtils.clearUser(userName);
            }
        }
    }
}
